<?php

namespace App\Jobs;

use App\Enums\CouponStatus;
use App\Models\NsSupplierGoodsCoupon;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class CouponChange implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    // 设置任务重试和超时参数
    public $tries = 3;
    public $maxExceptions = 2;
    public $timeout = 60; // 任务最长执行时间（秒）

    private $recordId;
    private $targetStatus;
    private $endTimestamp;

    public function __construct(int $recordId, int $targetStatus, ?int $endTimestamp = null)
    {
        $this->recordId = $recordId;
        $this->targetStatus = $targetStatus;
        $this->endTimestamp = $endTimestamp;
    }

    public function handle()
    {
        try {
            DB::transaction(function () {
                $query = NsSupplierGoodsCoupon::where('record_id', $this->recordId);

                switch ($this->targetStatus) {
                    case CouponStatus::PENDING:
                        // 激活优惠券：从未生效(1)变为未使用(2)
                        $query->where('state', CouponStatus::PENDING)
                            ->update(['state' => CouponStatus::ACTIVE]);
                        if ($this->endTimestamp) {
                            $expireJob = new self(
                                $this->recordId,
                                CouponStatus::ACTIVE
                            );

                            $expireJob->delay(Carbon::createFromTimestamp($this->endTimestamp))
                                ->onConnection('redis')
                                ->onQueue('CouponStatusChange');

                            dispatch($expireJob);
                        }
                        break;
                    case CouponStatus::ACTIVE:
                        // 分发过期任务
                        // 过期优惠券：从未使用(2)变为已过期(4)
                        $query->where('state', CouponStatus::ACTIVE)
                            ->update(['state' => CouponStatus::INEXPIRED]);
                        break;
                }
            });
        } catch (\Throwable $e) {
            $this->handleFailure($e);
        }
    }

    // 任务失败处理
    public function failed(\Throwable $exception)
    {
        Log::error("CouponChange job failed: Record {$this->recordId}, Status {$this->targetStatus}", [
            'error' => $exception->getMessage(),
            'trace' => $exception->getTraceAsString()
        ]);
    }

    // 自定义失败处理逻辑
    private function handleFailure(\Throwable $e)
    {
        // 可添加自定义重试逻辑或通知
        if ($this->attempts() < $this->tries) {
            $this->release(30); // 30秒后重试
            return;
        }

        throw $e;
    }
}
